/**
 * 城市及联业务逻辑 create by zhuchentong
 * 
 * @2017-04-28
 */
var d1 = require('deviceone')
var storage = require('util/storage')
var constant = require('config/constant')
var server = require('config/server')
var net = require('util/net')
var process = require('lib/process')
var log = require('util/log')
var initData = d1.sm("do_InitData");
var cityData
var cityDataSource = {}

/**
 * 获取城市信息数据
 */
function getCityJson() {
	if(!cityData){
		cityData = initData.readFileSync("initdata://city.json")
	}
	return cityData
}

/**
 * 获取城市数据
 * @param id
 * @returns
 */
function getCityData(id) {
	id = id || 1

	return cityData.filter(function(x) {
		return x.parentId === id
	}).map(function(x) {
		x.text = x.areaName
		return x
	})
}

/**
 * 更新城市控件数据源
 * @param id
 * @param source
 * @returns
 */
function updateCitySource(id, source) {
	source.removeAll()
	source.addData(getCityData(id))
}


/**
 * 获取城市名称
 * @param id
 * @returns
 */
module.exports.getCityName = function(id){
	var data = getCityJson()
	var city =  data.find(function(x) {
		return x.id == id
	})
	if(city){
		return city.areaName
	}else{
		return ''
	}
}

/**
 * 初始化城市及联业务逻辑
 */
module.exports.init = function(province, city, county) {
	if (!cityData) {
		getCityJson()
	}

	// 获取城市及联初始数据
	var provinceList = getCityData()
	var cityList = getCityData(provinceList[0].id)
	var countyList = getCityData(cityList[0].id)

	// 创建数据源
	var provinceSource = d1.mm('do_ListData')
	var citySource = d1.mm('do_ListData')
	var countySource = d1.mm('do_ListData')
	cityDataSource[province.getAddress()] = provinceSource
	cityDataSource[city.getAddress()] = citySource
	cityDataSource[county.getAddress()] = countySource

	// 绑定数据源
	provinceSource.addData(provinceList);
	province.bindItems(provinceSource)
	province.refreshItems();

	citySource.addData(cityList);
	city.bindItems(citySource)
	city.refreshItems();

	countySource.addData(countyList);
	county.bindItems(countySource)
	county.refreshItems();
	log.info(province.getAddress())
	// 添加数据监听
	province.on('selectChanged', function(index) {
		province.tag = provinceSource.getOne(index).id
		updateCitySource(provinceSource.getOne(index).id, citySource)
		city.refreshItems();
		updateCitySource(citySource.getOne(index).id, countySource)
		county.refreshItems();
	})

	// 添加数据监听
	city.on('selectChanged', function(index) {
		city.tag = citySource.getOne(index).id
		updateCitySource(citySource.getOne(index).id, countySource)
		county.refreshItems();
	})

	// 添加数据监听
	county.on('selectChanged', function(index) {
		county.tag = countySource.getOne(index).id
	})
	
	province.index = 0
	city.index = 0
	county.index = 0
}

/**
 * 获取城市id列表
 */
module.exports.getCityId = function() {
	var result = []
	for (var i = 0; i < arguments.length; i++) {
		var target = arguments[i]
		result.push(cityDataSource[target.getAddress()].getOne(target.index).id)
	}

	if (result.length == 1) {
		return result[0]
	} else {
		return result
	}
}
